/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.biz.service;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.BarcodeUtil;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.biz.dao.*;
import com.thinkgem.jeesite.modules.biz.entity.*;
import com.thinkgem.jeesite.modules.biz.form.BizOrderForm;
import com.thinkgem.jeesite.modules.biz.form.BizOrderOutForm;
import com.thinkgem.jeesite.modules.biz.form.BizOrderdetailForm;
import com.thinkgem.jeesite.modules.biz.vo.BizOrderDetailVo;
import com.thinkgem.jeesite.modules.biz.vo.BizOrderVo;
import com.thinkgem.jeesite.modules.biz.vo.ResultVO;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.enums.ResultEnum;
import com.thinkgem.jeesite.modules.sys.utils.AutoNameUtils;
import com.thinkgem.jeesite.modules.sys.utils.ResultVOUtil;
import org.apache.fop.apps.FOURIResolver;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;

/**
 * 订单Service
 * @author tiancheng
 * @version 2018-09-17
 */
@Service
@Transactional(readOnly = true)
public class BizOrderService extends CrudService<BizOrderDao, BizOrder> {

	@Autowired
	private BizOrderDao bizOrderDao;
	@Autowired
	private BizOrderdetailDao bizOrderdetailDao;
	@Autowired
	private BizBarcodeLogDao bizBarcodeLogDao;
	@Autowired
	private BizBarcodeDao bizBarcodeDao;
	@Autowired
	private BizGoodsDao bizGoodsDao;

	public BizOrder get(String id) {
		return super.get(id);
	}

	public List<BizOrder> findList(BizOrder bizOrder) {
		return super.findList(bizOrder);
	}

	public Page<BizOrder> findPage(Page<BizOrder> page, BizOrder bizOrder) {
		return super.findPage(page, bizOrder);
	}


	public List<BizOrder> findReceiveList(BizOrder bizOrder) {
		return bizOrderDao.findReceiveList(bizOrder);
	}

	public Page<BizOrder> findReceivePage(Page<BizOrder> page, BizOrder bizOrder) {
		bizOrder.setPage(page);
		page.setList(bizOrderDao.findReceiveList(bizOrder));
		return page;
	}

	@Transactional(readOnly = false)
	public void save(BizOrder bizOrder) {
		super.save(bizOrder);
	}

	@Transactional(readOnly = false)
	public void delete(BizOrder bizOrder) {
		super.delete(bizOrder);
	}


	/**
	 * 手机端获取出库的详情
	 *
	 * @param
	 * @return
	 * @author tiancheng
	 * @date 2018/9/18 15:36
	 */

	public BizOrderVo getApi(String name) {
		BizOrderVo bizOrderVo = bizOrderDao.getApi(name);
		if (null != bizOrderVo) {
			BizOrderdetail bizOrderdetail = new BizOrderdetail();
			bizOrderdetail.setOutboundOrderPid(bizOrderVo.getId());
			List<BizOrderDetailVo> bizOrderDetailVoList = bizOrderdetailDao.findListApi(bizOrderdetail);
			//查询该出库单下的商品的实际出库数（根据日志查询）
			for (BizOrderDetailVo bizOrderDetailVo : bizOrderDetailVoList) {
				BizBarcodeLog bizBarcodeLog = new BizBarcodeLog();
				bizBarcodeLog.setOrderId(bizOrderVo.getId());
				bizBarcodeLog.setGoodsId(bizOrderDetailVo.getGoodsId());
				Integer sum = bizBarcodeLogDao.selectSumByOrderIdAndGoodsId(bizBarcodeLog);
				if (null == sum) {
					sum = 0;
				}
				bizOrderDetailVo.setActualNumber(sum);
				Double quantity = Double.parseDouble(bizOrderDetailVo.getQuantity());
				bizOrderDetailVo.setQuantity(quantity.intValue() + "");
			}
			bizOrderVo.setBizOrderDetailVoList(bizOrderDetailVoList);
		}
		return bizOrderVo;
	}


	/**
	 * 接受CRM推送的订单
	 *
	 * @param
	 * @return
	 * @author tiancheng
	 * @date 2018/9/17 11:00
	 */
	@Transactional(readOnly = false)
	public void saveApi(BizOrderForm bizOrderForm) {
		BizOrder bizOrderInfo = bizOrderDao.get(bizOrderForm.getId());
		if (null == bizOrderInfo || null == bizOrderInfo.getId()) {
			BizOrder bizOrder = new BizOrder();
			BeanUtils.copyProperties(bizOrderForm, bizOrder);
			String name = AutoNameUtils.createAutoNameByTableName1("biz_order");
			bizOrder.setName(name);
			//生成条形码的地址
			String txmPath = exportDir() + name + "CKD.jpg";
			BarcodeUtil.createBarcode(name, txmPath);
			//修改出库单的条码路径
			if (txmPath.indexOf("userfiles") != -1) {
				String[] paths = txmPath.split("userfiles");
				bizOrder.setTmUrl("/userfiles" + paths[1]);
			}

			bizOrder.setOrderStatus("0");
			User user = new User();
			user.setId(bizOrderForm.getCreateBy());
			user.setName(bizOrderForm.getCreateByName());
			bizOrder.setCreateBy(user);
			//添加订单
			bizOrderDao.insert(bizOrder);
			//添加订单明细
			List<BizOrderdetailForm> bizOrderdetailFormList = bizOrderForm.getSmOrderdetailList();
			for (BizOrderdetailForm bizOrderdetailForm : bizOrderdetailFormList) {
				//查询商品的名称和编号
				BizOrderdetail bizOrderdetail = new BizOrderdetail();
				BeanUtils.copyProperties(bizOrderdetailForm, bizOrderdetail);

				bizOrderdetail.setSurplusQuantity(bizOrderdetailForm.getQuantity()); // 添加剩余出库数
				BizGoods bizGoods = new BizGoods();
				bizGoods.setGoodsCode(bizOrderdetailForm.getCode());
				List<BizGoods> bizGoodsList = bizGoodsDao.findList(bizGoods);
				bizGoods = bizGoodsList.get(0);
				bizOrderdetail.setProjectdetailId(bizGoods.getGoodsId());
				bizOrderdetail.setCode(bizGoods.getGoodsCode());
				bizOrderdetail.setProjectdetailName(bizGoods.getGoodsName());
				bizOrderdetailDao.insert(bizOrderdetail);
			}
		}
	}

	/**
	 * 接受CRM的优惠申请单推送
	 *
	 * @param
	 * @return
	 * @author tiancheng
	 * @date 2018/11/23 13:17
	 */
	@Transactional(readOnly = false)
	public void saveDiscountsOrder(BizOrderForm bizOrderForm) {
		BizOrder bizOrder = new BizOrder();
		BeanUtils.copyProperties(bizOrderForm, bizOrder);
		//不管是添加还是修改，直接先删除
		bizOrderDao.realDelete(bizOrder);

//		String name = AutoNameUtils.createAutoNameByTableName1("biz_order");
//		bizOrder.setName(name);
		//生成条形码的地址
		String txmPath = exportDir() + bizOrderForm.getName() + "CKD.jpg";
		BarcodeUtil.createBarcode(bizOrderForm.getName(), txmPath);
		//修改出库单的条码路径
		if (txmPath.indexOf("userfiles") != -1) {
			String[] paths = txmPath.split("userfiles");
			bizOrder.setTmUrl("/userfiles" + paths[1]);
		}

		User user = new User();
		user.setId(bizOrderForm.getCreateBy());
		user.setName(bizOrderForm.getCreateByName());
		bizOrder.setCreateBy(user);
		bizOrder.setCreateByName(bizOrderForm.getCreateByName());
		bizOrder.setAuditorName(bizOrderForm.getAuditorName());    //审核人名称
		bizOrder.setAuditDate(bizOrderForm.getAuditDate());    //审核日期
		bizOrder.setOrderGenre("10");// 出库单类型 标配
		bizOrder.setDeliverType("0"); //正常发货
		bizOrder.setOrderApprovalStatus("20"); //审核通过
		bizOrder.setOrderStatus("0");    //待出库
		bizOrder.setOrderType("0");    //正常出库
		bizOrder.setIsCanOut("1");    //可以出库
		//添加订单
		bizOrderDao.insert(bizOrder);
		//添加订单明细
		List<BizOrderdetailForm> bizOrderdetailFormList = bizOrderForm.getSmOrderdetailList();
		if (bizOrderdetailFormList != null && bizOrderdetailFormList.size() > 0) {
			for (BizOrderdetailForm bizOrderdetailForm : bizOrderdetailFormList) {
				//查询商品的名称和编号
				BizOrderdetail bizOrderdetail = new BizOrderdetail();
				BeanUtils.copyProperties(bizOrderdetailForm, bizOrderdetail);
				bizOrderdetail.setSurplusQuantity(bizOrderdetailForm.getQuantity()); // 添加剩余出库数

				BizGoods bizGoods = bizGoodsDao.getByGoodsCode(bizOrderdetailForm.getCode());
				if (bizGoods != null && StringUtils.isNotEmpty(bizGoods.getGoodsId())) {
					bizOrderdetail.setProjectdetailId(bizGoods.getGoodsId());
					bizOrderdetail.setCode(bizGoods.getGoodsCode());
					bizOrderdetail.setProjectdetailName(bizGoods.getGoodsName());
					bizOrderdetail.setCreateBy(user);
					bizOrderdetail.setCreateDate(bizOrder.getCreateDate());
					bizOrderdetail.setUpdateBy(user);
					bizOrderdetail.setUpdateDate(bizOrder.getUpdateDate());
					bizOrderdetailDao.insert(bizOrderdetail);
				}
			}
		}
	}


	/**
	 * 生成条形码的路径
	 * @author tiancheng
	 * @date 2018/9/5 14:02
	 * @param
	 * @return
	 */
	public String exportDir(){
		//默认传到系统管理员的明下
		String exportDir =  FileUtils.path(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + "1/files/exportFiles/" + DateUtils.getDate("yyyy-MM-dd") + "/");
		if (!new File(exportDir).exists()) {
			new File(exportDir).mkdirs();
		}
		return exportDir;
	}



	 /**
	  * 出库单的出库
	  * @author tiancheng  
	  * @date 2018/9/19 16:01
	  * @param
	  * @return
	  */
	@Transactional(readOnly = false)
	public ResultVO out(BizOrderOutForm bizOrderOutForm){
		//因为一个商品可能在多个条码上出库，所以查询根据商品id分组后的出库商品数量
		List<BizBarcodeLog> barcodeLogList = bizBarcodeLogDao.selectGroupGoodsId(bizOrderOutForm.getOrderId());
		//先判断是否全部出库完成
		BizOrderdetail bizOrderdetail = new BizOrderdetail();
		bizOrderdetail.setOutboundOrderPid(bizOrderOutForm.getOrderId());
		List<BizOrderdetail> bizOrderdetailListAll = bizOrderdetailDao.findList(bizOrderdetail);
		for (BizOrderdetail orderdetail:bizOrderdetailListAll) {
			boolean isNot = true;
			for (BizBarcodeLog barcodeLog:barcodeLogList) {
				//判断商品是否全部符合发货要求
				if(orderdetail.getProjectdetailId().equals(barcodeLog.getGoodsId())){
					isNot = false;
					//判断商品的出库数是否全部出库
					if(orderdetail.getQuantity() > Integer.valueOf(barcodeLog.getNumber())){
						return ResultVOUtil.error(ResultEnum.ORDER_DETAILED_INSUFFICIENT.getCode(),"有未出库的商品，请仔细检查");
					}
				}
			}
			//说明订单明细，没有匹配到出库日志，所以说该商品没有出库
			if(isNot){
				return ResultVOUtil.error(ResultEnum.ORDER_DETAILED_INSUFFICIENT.getCode(),"有未出库的商品，请仔细检查");
			}
		}
		//查询该订单的出库日志
		BizBarcodeLog bizBarcodeLog = new BizBarcodeLog();
		bizBarcodeLog.setOrderId(bizOrderOutForm.getOrderId());
		List<BizBarcodeLog> bizBarcodeLogList = bizBarcodeLogDao.findList(bizBarcodeLog);
		//修改条码上的信息
		for (BizBarcodeLog barcodeLog:bizBarcodeLogList) {
			Integer rizhi = Integer.valueOf(barcodeLog.getNumber());
			//只有酱料和冷链条码出库，其他的都是直接出库
			if(null != barcodeLog.getBarcodeId() && !barcodeLog.getBarcodeId().equals("")){
				//条码的信息
				BizBarcode bizBarcode = bizBarcodeDao.get(barcodeLog.getBarcodeId());
				Integer sum = Integer.valueOf(bizBarcode.getNumber());
				Integer waitNumber = Integer.valueOf(bizBarcode.getWaitNumber());
				Integer sumShen = sum-rizhi;
				Integer waitNumberShen = waitNumber - rizhi;
				//修改条码的剩余数和待出库数
				bizBarcode.setNumber(sumShen.toString());
				bizBarcode.setWaitNumber(waitNumberShen.toString());
				//如果剩余数为0，此条形码作废
				if(bizBarcode.getSurplusNumber().equals("0")){
					bizBarcode.setDelFlag("1");
					//删除条形码
					//FileUtils.delFile(bizBarcode.getUrl());
				}
				bizBarcodeDao.update(bizBarcode);
			}

			//修改商品的库存和待出库的数量
			BizGoods bizGoods = bizGoodsDao.get(barcodeLog.getGoodsId());
			Integer stockAmount = bizGoods.getStockAmount();//当前商品的库存数
			Integer waitStockAmount = bizGoods.getWaitStockAmount();//当前商品的待出库存数
			Integer shen = stockAmount - rizhi;
			Integer waitStockAmountShen = waitStockAmount - rizhi;
			bizGoods.setStockAmount(shen);
			bizGoods.setWaitStockAmount(waitStockAmountShen);
			bizGoodsDao.updateInfo(bizGoods);

			//修改出库单明细
			bizOrderdetail = new BizOrderdetail();
			bizOrderdetail.setOutboundOrderPid(barcodeLog.getOrderId());
			bizOrderdetail.setProjectdetailId(barcodeLog.getGoodsId());
			List<BizOrderdetail> bizOrderdetailList = bizOrderdetailDao.findList(bizOrderdetail);
			if(null != bizOrderdetailList){
				bizOrderdetail = bizOrderdetailList.get(0);

				//如果不是商品不足的话进行出库明细的状态修改
				if(!bizOrderdetail.getIsDeliver().equals("1")){
					//修改出库单的剩余出库数
					Integer surplusQuantity = bizOrderdetail.getSurplusQuantity();
					Integer surplusQuantityCha = surplusQuantity - rizhi;
					//判断该商品是否全部出库完成
					if(surplusQuantityCha == 0){
						bizOrderdetail.setIsDeliver("2");
					}else{
						bizOrderdetail.setIsDeliver("4");
					}
					bizOrderdetail.setSurplusQuantity(surplusQuantityCha);
					bizOrderdetailDao.update(bizOrderdetail);
				}
			}
			//修改日志为已操作
			bizBarcodeLogDao.delete(barcodeLog);
		}
		//出库验证已加，所以直接设置为全部出库
		BizOrder bizOrder = new BizOrder();
		bizOrder.setId(bizOrderOutForm.getOrderId());
		bizOrder.setOrderStatus("1");
		bizOrderDao.updateStatus(bizOrder);
		return ResultVOUtil.success();
	}

	@Transactional(readOnly = false)
    public void updateOrderApprovalAdopt(String id) {
		bizOrderDao.updateOrderApprovalAdopt(id);
		bizOrderDao.updateOrderApprovalAdopt(id+"F");
    }


	@Transactional(readOnly = false)
	public void discarded(String name) {
		List<BizOrder> orderList = selectByName(name);
		for (BizOrder order:orderList) {
			List<BizOrderdetail> bizOrderDetails = bizOrderdetailDao.findListByOrderId(order.getId());
			if(bizOrderDetails != null && bizOrderDetails.size() > 0){
				for (BizOrderdetail bizOrderDetail : bizOrderDetails) {
					Integer quantity = bizOrderDetail.getQuantity();	//数量
					String code = bizOrderDetail.getCode();	//商品code
					if(StringUtils.isNotEmpty(code)){
						//还原商品库存
						BizGoods bizGoods = bizGoodsDao.getByGoodsCode(code);
						if(bizGoods != null){
							Integer waitStockAmount = bizGoods.getWaitStockAmount();
							Integer sureStockAmount = bizGoods.getSureStockAmount();
							bizGoods.setWaitStockAmount(waitStockAmount-quantity);
							bizGoods.setSureStockAmount(sureStockAmount+quantity);
							bizGoodsDao.updateInfo(bizGoods);
						}
					}
					bizOrderdetailDao.delete(bizOrderDetail);
				}
			}
			bizOrderDao.realDelete(order);
		}
	}

	/**
	 * 根据id更新订单
	 * @param bizOrder
	 */
	@Transactional(readOnly = false)
    public void update(BizOrder bizOrder) {
		bizOrderDao.updateById(bizOrder);
    }

	@Transactional(readOnly = false)
	public void updateOrderApprovalAdoptYY(String id) {
		bizOrderDao.updateOrderApprovalAdopt(id);
	}


	 /**
	  * 根据订单的编号查询是否存在已出库的订单
	  * @author tiancheng
	  * @date 2018/12/7 15:34
	  * @param
	  * @return
	  */
	 public Integer selectCountByName(String name){
		 BizOrder bizOrder = new BizOrder();
		 bizOrder.setName(name);
		 return bizOrderDao.selectCountByName(bizOrder);
	 }


	public List<BizOrder> selectByName(String name){
		BizOrder bizOrder = new BizOrder();
		bizOrder.setName(name);
		return bizOrderDao.selectByName(bizOrder);
	}
}